package com.sh.shanhuo.activity;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.sh.shanhuo.R;
import com.sh.shanhuo.adapter.ContentAdapter;
import com.sh.shanhuo.adapter.SearchBoxAdapter;
import com.sh.shanhuo.bean.BoxSearchBean;
import com.sh.shanhuo.database.web.WebInfoEntity;
import com.sh.shanhuo.listener.GsonObjectCallback;
import com.sh.shanhuo.utils.OkHttpUtil;
import com.sh.shanhuo.utils.ScreenSwitch;
import com.sh.shanhuo.utils.SearchUtils;
import com.sh.shanhuo.utils.Tools;
import com.sh.shanhuo.view.CommonItemDecoration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;

public class SearchActivity extends BaseActivity {
    private String text;
    private int fromFlag;
    private EditText search;
    private TextView emptyTips;
    private ContentAdapter contentAdapter;
    private SearchBoxAdapter searchBoxAdapter;
    private final List<WebInfoEntity> webInfoEntities = new ArrayList<>();
    private final List<BoxSearchBean.DataBean> dataBeans = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        super.initView();
        getBundle();
        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> finish());
        search = findViewById(R.id.search);
        emptyTips = findViewById(R.id.emptyTips);
        TextView clear = findViewById(R.id.clear);
        search.setText(text);
        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    clear.setVisibility(View.VISIBLE);
                } else {
                    clear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (fromFlag == 1) {
                    checkSite(s.toString());
                } else {
                    getCateList(s.toString());
                }
            }
        });
        clear.setOnClickListener(v -> search.setText(""));
        initSearchView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        search.clearFocus();
    }

    private void initSearchView() {
        RecyclerView searchView = findViewById(R.id.searchView);
        if (fromFlag == 1) {
            searchView.setLayoutManager(new GridLayoutManager(mContext, 2));
            searchView.addItemDecoration(new CommonItemDecoration(Tools.dp2px(mContext, 10),
                    Tools.dp2px(mContext, 10), Tools.dp2px(mContext, 10)));
            contentAdapter = new ContentAdapter(this, null);
            searchView.setAdapter(contentAdapter);
            checkSite(text);
            contentAdapter.setOnItemClickListener((adapter, view, position) -> {
                if (TextUtils.isEmpty(webInfoEntities.get(position).webLink)) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("url", webInfoEntities.get(position).webLink);
                bundle.putString("id", webInfoEntities.get(position).webId);
                ScreenSwitch.startActivity(SearchActivity.this, WebActivity.class, bundle);
            });
        } else if (fromFlag == 2) {
            getCateList(text);
            LinearLayoutManager manager = new LinearLayoutManager(mContext);
            manager.setOrientation(LinearLayoutManager.VERTICAL);
            searchView.setLayoutManager(manager);
            searchView.addItemDecoration(new CommonItemDecoration(Tools.dp2px(mContext, 10),
                    Tools.dp2px(mContext, 10), Tools.dp2px(mContext, 10)));
            searchBoxAdapter = new SearchBoxAdapter(this, null);
            searchView.setAdapter(searchBoxAdapter);
            searchBoxAdapter.setOnItemClickListener((adapter, view, position) -> {
                Bundle bundle = new Bundle();
                bundle.putString("id", dataBeans.get(position).getId());
                bundle.putString("webName", dataBeans.get(position).getWebName());
                bundle.putString("logoUrl", dataBeans.get(position).getLogoUrl());
                bundle.putString("introduce", dataBeans.get(position).getIntroduce());
                bundle.putString("webUrl", dataBeans.get(position).getWebUrl());
                ScreenSwitch.startActivity(SearchActivity.this,
                        RecommendationInfoActivity.class, bundle);
            });
        }
    }

    private void getBundle() {
        Intent intent = getIntent();
        if (intent == null)
            return;
        Bundle bundle = intent.getExtras();
        if (bundle == null)
            return;
        text = bundle.getString("searchText", "");
        fromFlag = bundle.getInt("fromFlag");
    }

    private void checkSite(String text) {
        webInfoEntities.clear();
        for (WebInfoEntity webInfoEntity : SearchUtils.getWebInfoEntities()) {
            if (webInfoEntity.webName.contains(text)) {
                webInfoEntities.add(webInfoEntity);
            }
        }
        if (webInfoEntities.size() == 0) {
            emptyTips.setVisibility(View.VISIBLE);
            return;
        }
        emptyTips.setVisibility(View.GONE);
        contentAdapter.setNewData(webInfoEntities);
    }

    private void getCateList(String text) {
        if (dataBeans.size() > 0) {
            dataBeans.clear();
        }
        if (TextUtils.isEmpty(text)) {
            emptyTips.setVisibility(View.VISIBLE);
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("webName", text);
        OkHttpUtil.getInstance().postForm(OkHttpUtil.IP + OkHttpUtil.SEARCH_LIST, params, new GsonObjectCallback<BoxSearchBean>() {
            @Override
            public void onUi(BoxSearchBean bean) {
                if (bean.getCode() == 200 && bean.getData() != null) {
                    dataBeans.addAll(bean.getData());
                    if (dataBeans.size() == 0) {
                        emptyTips.setVisibility(View.VISIBLE);
                        return;
                    }
                    emptyTips.setVisibility(View.GONE);
                    searchBoxAdapter.setNewData(dataBeans);
                }
            }

            @Override
            public void onFailed(Call call, IOException e) {
                ToastUtils.showShort("请求失败，请检查网络错误");
            }
        });
    }
}
